﻿/*
 * Copyright (c) 2009 Mustafa OZCAN (http://www.mustafaozcan.net) Dual licensed
 * under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
 * (http://www.opensource.org/licenses/gpl-license.php) licenses. Version: 1.0.2
 * Requires: jquery.1.3+
 */
var _scing = false;
jQuery.fn.fixedtableheader = function(options){
	var settings = jQuery.extend({
		clearForm : false
	}, options);

	this.each(function(i){
		var $tbl = $(this);
		var $tblhfixed = $tbl.find('thead');
		var tbleft = $tbl.offset().left;
		// 克隆表
		var $clonedTable = $tbl.clone();
		$clonedTable.attr('id', '')
			.find('thead').attr('id', '').end()
			.find('tfoot').remove().end()
			.find('tbody').attr('id', '').css('visibility', 'collapse')
			.find('tr:gt(0)').remove().end()
			.find('tr:eq(0)').find('th,td').css('border', 'none');
		// 清除可能存在的表单项
		if(settings.clearForm){
			$clonedTable.find('thead').find('input,select,button,textarea').each(function(){
				var p = $(this).parent();
				if(p[0].tagName == 'td' || p[0].tagName == 'th'){
					p.empty();
				}else{
					p.remove();
				}
			});
		}
		var tblwidth = $tbl.outerWidth();
		var ie6 = (jQuery.browser.msie && jQuery.browser.version == '6.0');
		$clonedTable.attr('id', 'fixedtableheader'+i).css({
				'position'	: ie6 ? 'absolute' : 'fixed',
				'top'		: '0',
				'left'		: $tbl.offset().left
			}).append().width(tblwidth).hide().appendTo($('body'));
		// 窗口滚动事件
		$(window).scroll(function(){
			if(_scing){
				// console.log('running');
				return false;
			}
			// console.log('run');
			_scing = true;
			_scroll();
			setTimeout(function(){
				_scroll();
				_scing = false;
			}, 100);
		});
		function _scroll(){
			var sctop = $(window).scrollTop();
			var elmtop = $tbl.offset().top;
			if(sctop > elmtop && sctop <= (elmtop + $tbl.height() - $tblhfixed.height())){
				$clonedTable.show();
				if(ie6){
					$clonedTable.css({'top' : sctop });
				}
				var scleft = $(window).scrollLeft();
				if(scleft > 0){
					$clonedTable.css({'left' : tbleft - scleft });
				}else{
					$clonedTable.css({'left' : tbleft });
				}
			}else{
				$clonedTable.hide();
			}
		}
		$(window).resize(function(){
			if($clonedTable.outerWidth() != $tbl.outerWidth()){
				/*$tblhfixed.find('th').each(function(index){
					var w = $(this).width();
					$(this).css('width', w);
					$clonedTable.find('th').eq(index).css('width', w);
				});*/
				$clonedTable.width($tbl.outerWidth());
			}
			//$clonedTable.css('left', tbleft);
		});

	});
	

};